<template>
	<div class="course-management">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-input v-model="searchParams.title" placeholder="请输入课程标题" clearable @clear="handleSearch"
				@keyup.enter="handleSearch" style="width: 300px; margin-right: 10px" />
			<el-button type="primary" @click="handleSearch">搜索</el-button>
			<el-button @click="resetSearch">重置</el-button>
		</div>

		<!-- 表格区域 -->
		<el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
			@selection-change="handleSelectionChange" @row-click="handleRowClick" v-loading="loading">
			<el-table-column type="selection" width="55" />

			<el-table-column prop="title" label="课程标题" width="120" />

			<el-table-column prop="fee" label="课程费用" sortable :sort-orders="['ascending', 'descending']"
				:sort-by="sortByFee" width="120">
				<template #default="scope">
					¥{{ scope.row.fee }}
				</template>
			</el-table-column>

			<el-table-column prop="startTime" label="开始时间" sortable :sort-orders="['ascending', 'descending']"
				:sort-by="sortByStartTime" width="180" />

			<el-table-column prop="createdAt" label="创建时间" sortable :sort-orders="['ascending', 'descending']"
				:sort-by="sortByCreatedAt" width="180" />

			<el-table-column prop="updatedAt" label="更新时间" sortable :sort-orders="['ascending', 'descending']"
				:sort-by="sortByUpdatedAt" width="180" />

			<el-table-column prop="status" label="状态" width="120" :filters="[
          { text: '未开始', value: 0 },
          { text: '已开始', value: 1 },
          { text: '已结束', value: 2 },
          { text: '已取消', value: 3 },
        ]" :filter-method="filterStatus" filter-placement="bottom-end">
				<template #default="scope">
					<el-tag :type="statusTagType(scope.row.status)" disable-transitions>
						{{ statusText(scope.row.status) }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="enrolledCount" label="报名人数" sortable :sort-orders="['ascending', 'descending']"
				:sort-by="sortByEnrolledCount" />

			<el-table-column prop="peopleLimit" label="人数限制" width="120" :filters="[
{ text: '不限制', value: -1 },
{ text: '有限制', value: 'positive' }  // 特殊值表示>0的情况
  ]" :filter-method="filterPeopleLimit">
				<template #default="scope">
					{{ formatPeopleLimit(scope.row.peopleLimit) }}
				</template>
			</el-table-column>


			<el-table-column label="操作" width="180" fixed="right">
				<template #default="scope">
					<el-button size="small" @click.stop="handleEdit(scope.row.id)">编辑</el-button>
					<el-button size="small" type="danger" @click.stop="handleDelete(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 批量操作按钮 -->
		<div class="batch-actions" v-if="multipleSelection.length > 0">
			<el-button @click="toggleSelection()">取消选择</el-button>
			<el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
		</div>

		<!-- 分页 -->
		<div class="pagination" v-else>
			<el-pagination v-model:current-page="searchParams.pageNo" v-model:page-size="searchParams.pageSize"
				:page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
				:total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<script setup>
	import {
		getCoursesPage,
		updateCourses,
		deleteListCourses
	} from '@/api/course.js'

	import {
		ref,
		reactive,
		onMounted,
		onBeforeUnmount
	} from 'vue'

	import {
		useRouter
	} from 'vue-router'

	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'

	/**
	 * 通过 JavaScript 动态计算​样式
	 */
	const adjustTableHeight = () => {
		const headerHeight = document.querySelector('.search-bar')?.offsetHeight || 0
		const paginationHeight = document.querySelector('.pagination')?.offsetHeight || 60
		const table = document.querySelector('.el-table')
		if (table) {
			table.style.height = `calc(100vh - ${headerHeight + paginationHeight + 40}px)`
		}
	}

	/**
	 * 初始化加载数据
	 */
	onMounted(() => {
		adjustTableHeight()
		window.addEventListener('resize', adjustTableHeight)
		fetchCourses()
	})

	onBeforeUnmount(() => {
		window.removeEventListener('resize', adjustTableHeight)
	})

	const router = useRouter()
	const multipleTableRef = ref()
	const multipleSelection = ref([])
	const tableData = ref([])
	const total = ref(0)
	const loading = ref(false)

	/**
	 * 初始化搜索参数
	 */
	const searchParams = reactive({
		title: '',
		pageNo: 1,
		pageSize: 10,
		startTimeIsAsc: false,
		startTimeEnabled: false,
		createdIsAsc: false,
		createdEnabled: false,
		updatedIsAsc: false,
		updatedEnabled: false,
		feeIsAsc: false,
		feeEnabled: false,
		status: null,
		statusFilterEnabled: false
	})

	/**
	 * 获取课程列表
	 */
	const fetchCourses = async () => {
		loading.value = true
		try {
			const res = await getCoursesPage(searchParams)
			tableData.value = res.data.records
			total.value = res.data.total
		} catch (error) {
			ElMessage.error('获取课程列表失败')
		} finally {
			loading.value = false
		}
	}

	/**
	 * 搜索
	 */
	const handleSearch = () => {
		searchParams.pageNo = 1
		fetchCourses()
	}

	/**
	 * 重置搜索
	 */
	const resetSearch = () => {
		searchParams.title = ''
		searchParams.pageNo = 1
		searchParams.status = null
		searchParams.statusFilterEnabled = false
		resetSorting()
		fetchCourses()
	}

	/**
	 * 重置排序
	 */
	const resetSorting = () => {
		searchParams.startTimeEnabled = false
		searchParams.createdEnabled = false
		searchParams.updatedEnabled = false
		searchParams.feeEnabled = false
	}

	/**
	 * 分页大小变化
	 */
	const handleSizeChange = (val) => {
		searchParams.pageSize = val
		fetchCourses()
	}

	/**
	 * 当前页变化
	 */
	const handleCurrentChange = (val) => {
		searchParams.pageNo = val
		fetchCourses()
	}

	/**
	 * 多选处理
	 */
	const handleSelectionChange = (val) => {
		multipleSelection.value = val
	}

	/**
	 * 清除选择
	 */
	const toggleSelection = (rows) => {
		if (rows) {
			rows.forEach((row) => {
				multipleTableRef.value.toggleRowSelection(row, undefined)
			})
		} else {
			multipleTableRef.value.clearSelection()
		}
	}

	/**
	 * 状态筛选
	 */
	const filterStatus = (value, row) => {
		return row.status === value
	}

	/**
	 * 人数限制状态筛选
	 */
	const filterPeopleLimit = (value, row) => {
		if (value === -1) {
			return row.peopleLimit === -1
		} else if (value === 'positive') {
			return row.peopleLimit > 0
		}
		return true
	}

	/**
	 * 显示限制人数的状态
	 */
	const formatPeopleLimit = (peopleLimit) => {
		return peopleLimit === -1 ? '不限制' : peopleLimit
	}

	/**
	 * 状态标签类型
	 */
	const statusTagType = (status) => {
		switch (status) {
			case 0:
				return 'warning' // 未开始
			case 1:
				return 'success' // 已开始
			case 2:
				return 'info' // 已结束
			case 3:
				return 'danger' // 已取消
			default:
				return ''
		}
	}

	/**
	 * 状态文本
	 */
	const statusText = (status) => {
		switch (status) {
			case 0:
				return '未开始'
			case 1:
				return '已开始'
			case 2:
				return '已结束'
			case 3:
				return '已取消'
			default:
				return '未知'
		}
	}

	/**
	 * 报名人数排序
	 */
	const sortByEnrolledCount = (row) => {
		parseFloat(row.peopleLimit)
	}
	/**
	 * 课程费用排序
	 */
	const sortByFee = (row, sortOrder) => {
		parseFloat(row.fee)
	}
	/**
	 * 开课时间排序
	 */
	const sortByStartTime = (row) => {
		new Date(row.startTime).getTime()
	}
	/**
	 * 创建时间排序
	 */
	const sortByCreatedAt = (row) => {
		new Date(row.createdAt).getTime()
	}
	/**
	 * 修改时间排序
	 */
	const sortByUpdatedAt = (row) => {
		new Date(row.updatedAt).getTime()
	}

	/**
	 * 表格排序变化
	 */
	const handleSortChange = ({
		column,
		prop,
		order
	}) => {
		resetSorting()

		switch (prop) {
			case 'startTime':
				searchParams.startTimeEnabled = true
				searchParams.startTimeIsAsc = order === 'ascending'
				break
			case 'createdAt':
				searchParams.createdEnabled = true
				searchParams.createdIsAsc = order === 'ascending'
				break
			case 'updatedAt':
				searchParams.updatedEnabled = true
				searchParams.updatedIsAsc = order === 'ascending'
				break
			case 'fee':
				searchParams.feeEnabled = true
				searchParams.feeIsAsc = order === 'ascending'
				break
		}

		fetchCourses()
	}

	/**
	 * 点击详情
	 */
	const handleRowClick = (row) => {
		router.push(`/course/${row.id}`)
	}

	/**
	 * 编辑课程
	 */
	const handleEdit = (id) => {
		router.push(`/course/edit/${id}`)
	}

	/**
	 * 删除课程
	 */
	const handleDelete = async (id) => {
		try {
			await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
				type: 'warning'
			})
			await deleteListCourses(Array.of(id))
			ElMessage.success('删除成功')
			await fetchCourses()
		} catch (error) {
			console.log('取消删除')
		}
	}

	/**
	 * 批量删除
	 */
	const handleBatchDelete = async () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请至少选择一项')
			return
		}

		try {
			await ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}项吗？`, '提示', {
				type: 'warning'
			})
			const ids = multipleSelection.value.map(item => item.id)
			await deleteListCourses(ids)
			ElMessage.success('批量删除成功')
			toggleSelection()
			await fetchCourses()
		} catch (error) {
			console.log('取消批量删除')
		}
	}
</script>

<style scoped>
	.course-management {
		height: calc(100vh - 40px);
		/* 40px 是 el-tabs 标题栏的预估高度 */
		display: flex;
		flex-direction: column;
		/* 继承父容器高度 */
		height: 100%;
		min-height: 0;
		overflow-y: auto;
	}

	.search-bar {
		margin-bottom: 20px;
		flex-shrink: 0;
	}

	.table-container {
		flex: 1;
		overflow: auto;
		margin-bottom: 20px;
	}

	.pagination {
		position: static;
		/* 确保不是fixed或absolute */
		overflow: visible;
	}

	.el-table {
		max-height: 72vh;
		flex: 1;
		/* 表格最大高度为视口高度的70% */
		overflow-y: auto;
	}

	.batch-actions {
		margin: 20px 0;
		flex-shrink: 0;
	}

	.pagination-container {
		flex-shrink: 0;
		background: #fff;
		padding: 16px 0;
		position: sticky;
		bottom: 0;
		z-index: 1;
	}

	/* 响应式调整 */
	@media screen and (max-width: 1200px) {
		.search-bar {
			flex-wrap: wrap;
			gap: 10px;
		}

		.search-bar .el-input {
			width: 100% !important;
			margin-right: 0 !important;
		}
	}

	.course-management {
		min-height: 100vh;
		overflow: auto;
	}
</style>